//  设备添加
//  ZYDeviceAddVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/8.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYDeviceAddVC.h"
#import "ZYViewUtils.h"
#import "ZYAlterMessageView.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "HFSmartLink.h"
#import "ZYDeviceViewModel.h"
#import "ZYDeviceModifyVC.h"
#import <SystemConfiguration/CaptiveNetwork.h>

@interface ZYDeviceAddVC ()
@property(nonatomic,strong) UITextField *ssidTextField;
@property(nonatomic,strong) UITextField *passwordTextField;
@property(nonatomic,strong) UIButton *confirmBtn;
@property(nonatomic,strong) UILabel *bottomLabel;
@property(nonatomic,strong) ZYChangeLanguage *language;
@property(nonatomic,strong) ZYAlterMessageView *alterMessageView;
@property(nonatomic,copy) NSString *SSID;
@property(nonatomic,strong) HFSmartLink *smtlk;
@property(nonatomic,copy) NSString *ip;
@property(nonatomic,copy) NSString *mac;
@property(nonatomic,assign) BOOL isConnecting;
@property(nonatomic,strong) ZYDeviceViewModel *viewModel;
@end

@implementation ZYDeviceAddVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_HOME_EDIT_DEVICE_ADD_DEVICE];
    [self getWifi];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.alterMessageView close];
    [_smtlk closeWithBlock:^(NSString *closeMsg, BOOL isOK) {
        if(!isOK){
            NSLog(@"%@",closeMsg);
        }
    }];
}

-(void)setup{
    _language = [ZYChangeLanguage sharedZYChangeLanguage];
    [self setupView];
    [self setupTap];
    [self setupBindView];
    _smtlk = [HFSmartLink shareInstence];
    _smtlk.isConfigOneDevice = YES;
}

-(void)setupView{
    _ssidTextField = [ZYViewUtils setupTextFieldWithLeftTitle:@"SSID" placeholder:@""];
    _passwordTextField = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_LOGIN_PASSWORD_PLACEHOLDER] placeholder:[_language getStringByKey:LC_DEVICE_ADD_PLACEHOLDER_PASSWORD]];
    CGFloat padding = 15;
    //设备ID
    [self.view addSubview:_ssidTextField];
    _ssidTextField.top = self.navigationView.bottom +5;
    _ssidTextField.centerX = self.view.centerX;
    _ssidTextField.enabled = NO;
    
    //密码
    [self.view addSubview:_passwordTextField];
    _passwordTextField.top = _ssidTextField.bottom + padding;
    _passwordTextField.centerX = self.view.centerX;
    _passwordTextField.text = @"";
    
    _confirmBtn = [ZYViewUtils setupConfirmBtn];
    [self.view addSubview:_confirmBtn];
    _confirmBtn.centerX = self.view.centerX;
    _confirmBtn.top = _passwordTextField.bottom + 25;
    [_confirmBtn addTarget:self action:@selector(doConfirm:) forControlEvents:UIControlEventTouchUpInside];
    [_confirmBtn setTitle:[_language getStringByKey:LC_DEVICE_ADD_BTN_TITLE_LINK] forState:UIControlStateNormal];
    
    _bottomLabel = [[UILabel alloc] init];
    _bottomLabel.textAlignment = NSTextAlignmentLeft;
    _bottomLabel.textColor = RGBA(153, 153, 153, 1);
    _bottomLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_bottomLabel];
    _bottomLabel.numberOfLines = 0;
    _bottomLabel.text = [_language getStringByKey:LC_DEVICE_ADD_LABEL_REMIND];
    _bottomLabel.size = CGSizeMake(self.view.width - 30, CGFLOAT_MIN);
    _bottomLabel.bottom = _confirmBtn.bottom + 25;
    _bottomLabel.centerX = self.view.centerX;
    NSDictionary *attributes = @{NSFontAttributeName:_bottomLabel.font,};
    CGSize size = [_bottomLabel.text boundingRectWithSize:CGSizeMake(_bottomLabel.width,CGFLOAT_MAX)
                                      options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    _bottomLabel.height = size.height;
}

-(void)setupBindView{
    @weakify(self);
    [self.viewModel.deviceConnectCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        NSString *mac = [x objectForKey:@"mac"];
        NSString *ip = [x objectForKey:@"ip"];
        BOOL success = [[x objectForKey:@"success"] boolValue];
        BOOL isAdd = [[x objectForKey:@"is_add"] boolValue];
        if(success){
            [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_DEVICE_CONNECT_SUCCESS]];
            [self goToAdd:ip mac:mac];
        }else{
            if(isAdd){
                [self alertViewWithIp:ip mac:mac];
            }else{
                [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:@"code_5003"]];//设备不在线
            }
        }
    }];
    [self.viewModel.deviceConnectCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
    }];
    //监听状态
    [[self.viewModel.deviceConnectCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
    
    // 设置网络状态变化回调
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        @strongify(self);
        if(status == AFNetworkReachabilityStatusReachableViaWiFi){
            //wifi
            [self.alterMessageView close];
            [self getWifi];
        }else{
            self.SSID = @"";
            self.ssidTextField.text = @"";
            [self.alterMessageView showOrHidden];
        }
    }];
    // 启动网络状态监听
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

-(void)alertViewWithIp:(NSString *)ip mac:(NSString *)mac{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[language getStringByKey:LC_DEVICE_EXIST_PROMPT] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_ALERT_CONTER_BTN_CONFIRM] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self goToAdd:ip mac:mac];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_ALERT_CONTER_BTN_CANCEL] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        return;
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)goToAdd:(NSString *)ip mac:(NSString *)mac{
    ZYDeviceModifyVC *vc = [[ZYDeviceModifyVC alloc] init];
    vc.mac = mac;
    vc.ip = ip;
    vc.isModify = NO;//添加操作
    vc.deviceType = _deviceType;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)getWifi{
//    NSDictionary *ifs = [self fetchSSIDInfo];
//    NSString *ssid = [ifs objectForKey:@"SSID"];
    NSString *ssid = [self wifiSSID];
    if (!NULLString(ssid)){
        _SSID = ssid;
        self.ssidTextField.text = ssid;
        [self.alterMessageView close];
    }else{
        [self.alterMessageView showOrHidden];
    }
}

-(NSString *)wifiSSID {
    
    NSString *ssid = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            ssid = info[@"SSID"];
        }
    }
    return ssid;
}

-(void)doConfirm:(UIButton *)button{
    [self dismissKeyboard];
    if(NULLString(_ssidTextField.text)){
        [self.alterMessageView showOrHidden];
        return;
    }
    self.viewModel.ssid = _ssidTextField.text;
    self.viewModel.password = _passwordTextField.text;
    self.viewModel.smtlk = _smtlk;
    [self.viewModel.deviceConnectCommand execute:nil];
}

#pragma mark - Getter
-(ZYAlterMessageView *)alterMessageView{
    if(!_alterMessageView){
        _alterMessageView = [[ZYAlterMessageView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H)];
        [self.view addSubview:_alterMessageView];
    }
    return _alterMessageView;
}

-(ZYDeviceViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYDeviceViewModel alloc] init];
    }
    return _viewModel;
}
@end
